/* eslint-disable */
import Factory from "../core/factory";
import Asserts from "../core/asserts";
import TextUtils from "../layers/text-utils";

/**
 * 数据格式化函数
 */
export type FormatType = (val: any, def?: string) => string;

class Formatter extends Factory<FormatType> {

    /**
     * 文本格式化函数
     *
     * 将输入值转为特定的格式之后进行输出:
     * - 如果原始数据为空，或者转换失败，则使用默认值，
     * - 如果默认值不存在，则使用原始值
     *
     * @param name - 格式化函数名称
     * @param val - 需要格式化的数据
     * @param def - 需要格式化的数据
     * @returns 格式化之后的结果
     */
    format(name: string, val: any, def: string = '') {
        try {
            const fun: FormatType = super.get(name);
            Asserts.isTypeOf('function', fun, 'formatter is not a function: ' + fun)
            return fun(val, def);
        } catch (e) {
            console.error(e);
            return def;
        }
    };
}


const formatter = new Formatter();

export type FormatterKey =
    | "time"
    | "date"
    | "datetime"
    | "compact-time"
    | "compact-date"
    | "compact-datetime"
    | "us-num"
    | "round"
    | "round2"
    | "myriad"
    | string;// 允许扩展当前未定义的字符串格式

// 增加一大堆内置的字符串格式化函数
formatter.put("time", TextUtils.time);
formatter.put("date", TextUtils.date);
formatter.put("datetime", TextUtils.datetime);
formatter.put("compact-time", TextUtils.compactTime);
formatter.put("compact-date", TextUtils.compactDate);
formatter.put("compact-datetime", TextUtils.compactDatetime);
formatter.put("us-num", TextUtils.numWithCommas);
formatter.put("round", TextUtils.round);
formatter.put("round2", TextUtils.round2);
formatter.put("myriad", TextUtils.myriad);

export default formatter;